﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Odbc;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using RSDataEdit;

namespace BugTracker
{
    public partial class mainForm : Form
    {
        public mainForm()
        {
            InitializeComponent();
            mainEdit.DataGrid = dataGridView1;
            mainEdit.Object = RSObjects.TaskList;
        }

        private DataEdit mainEdit = new DataEdit();

        private void LoadPositionFromReg()
        {
            RegistryKey key = Registry.CurrentUser.OpenSubKey(constants.RegisterHome);
            if (key != null)
            {
                int top = Int32.Parse(key.GetValue("WindowTop", 0).ToString());
                int left = Int32.Parse(key.GetValue("WindowLeft", 0).ToString());
                int height = Int32.Parse(key.GetValue("WindowHeight", 300).ToString());
                int width = Int32.Parse(key.GetValue("WindowWidth", 300).ToString());
                bool maximized = Int32.Parse(key.GetValue("IsWindowMaximized", 0).ToString()) != 0;
                key.Close();
                int r_left = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Left;
                int r_top = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Top;
                int r_height = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height;
                int r_width = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width;
                // Проверяю и корректирую, если нужно, размеры по оси X
                if (left < r_left)
                    left = r_left;
                if ((left + width) > r_width)
                {
                    int toLeft = left + width - r_width;
                    if (toLeft > left)
                    {
                        left = r_left;
                        width = r_width;
                    }
                    else
                        left = left - toLeft;
                };
                // Проверяю и корректирую, если нужно, размеры по оси Y
                if (top < r_top)
                    top = r_top;
                if ((top + height) > r_height)
                {
                    int toUp = top + height - r_height;
                    if (toUp > top)
                    {
                        top = r_top;
                        height = r_height;
                    }
                    else
                        top = top - toUp;
                };

                this.Width = width;
                this.Height = height;
                this.Top = top;
                this.Left = left;
                if (maximized)
                    this.WindowState = FormWindowState.Maximized;
            };
        }
        private void SavePositionToReg()
        {
            RegistryKey key = Registry.CurrentUser.OpenSubKey(constants.RegisterHome, RegistryKeyPermissionCheck.ReadWriteSubTree);
            if (key == null)
                key = Registry.CurrentUser.CreateSubKey(constants.RegisterHome, RegistryKeyPermissionCheck.ReadWriteSubTree);
            if (key != null)
            {
                if (WindowState != FormWindowState.Maximized)
                {
                    key.SetValue("WindowTop", Top, RegistryValueKind.DWord);
                    key.SetValue("WindowLeft", Left, RegistryValueKind.DWord);
                    key.SetValue("WindowHeight", Height, RegistryValueKind.DWord);
                    key.SetValue("WindowWidth", Width, RegistryValueKind.DWord);
                    key.SetValue("IsWindowMaximized", 0, RegistryValueKind.DWord);
                }
                else
                    key.SetValue("IsWindowMaximized", 1, RegistryValueKind.DWord);
                key.Close();
            };
        }
        private void SetMenuActive()
        {
            if (DBWork.Active)
            {
                connectToolStripMenuItem.Enabled = false;
                dissconnectToolStripMenuItem.Enabled = true;
            } else
            {
                connectToolStripMenuItem.Enabled = true;
                dissconnectToolStripMenuItem.Enabled = false;
            }
        }
        private void mainForm_Load(object sender, EventArgs e)
        {
            LoadPositionFromReg();
        }
        private void mainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            SavePositionToReg();
            DBWork.Disconnect();
        }
        private void mainForm_Shown(object sender, EventArgs e)
        {
            connectToolStripMenuItem_Click(this, null);
        }
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void connectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (DBWork.Active)
            {
                SetMenuActive();
                return;
            };
            // Получаю настройки из реестра
            String UserName = "";
            String Password = "";
            String DSN = "";
            bool RememberMe = false;

            RegistryKey key = Registry.CurrentUser.OpenSubKey(constants.RegisterHome + "Login");
            if (key != null)
            {
                UserName = key.GetValue("UserName", "").ToString();
                Password = key.GetValue("Password", "").ToString();
                DSN = key.GetValue("DSN", "").ToString();
                RememberMe = Int32.Parse(key.GetValue("RememberMe", 0).ToString()) != 0;
                key.Close();
            };
            if (RememberMe && e == null)
            {
                DBWork.DSN = DSN;
                if (!DBWork.Connect(UserName, Password))
                    MessageBox.Show(DBWork.ErrorStr, "Connection Error", MessageBoxButtons.OK); 
            };

            if (!DBWork.Active)
            {
                Forms.connectForm connForm = new Forms.connectForm();
                connForm.UserName = UserName;
                connForm.Password = "";
                connForm.DSN = DSN;
                connForm.RememberMe = RememberMe;
                if (connForm.ShowDialog(this) == DialogResult.OK)
                {
                    key = Registry.CurrentUser.OpenSubKey(constants.RegisterHome + "Login", RegistryKeyPermissionCheck.ReadWriteSubTree);
                    if (key == null)
                        key = Registry.CurrentUser.CreateSubKey(constants.RegisterHome + "Login", RegistryKeyPermissionCheck.ReadWriteSubTree);
                    if (key != null)
                    {
                        key.SetValue("UserName", connForm.UserName, RegistryValueKind.String);
                        key.SetValue("DSN", connForm.DSN, RegistryValueKind.String);
                        if (connForm.RememberMe)
                        {
                            key.SetValue("Password", connForm.Password, RegistryValueKind.String);
                            key.SetValue("RememberMe", 1, RegistryValueKind.DWord);
                        } else
                        {
                            key.SetValue("Password", "", RegistryValueKind.String);
                            key.SetValue("RememberMe", 0, RegistryValueKind.DWord);
                        }
                        key.Close();
                    };
                };
                connForm.Dispose();
            };
            SetMenuActive();

            ActivateData();
        }
        private void dissconnectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DBWork.Disconnect();
            SetMenuActive();
            ActivateData();
        }

        private void ActivateData()
        {
            mainEdit.Active = DBWork.Active;
        }

        private void mainForm_SizeChanged(object sender, EventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                notifyIcon1.Visible = true;
                Hide();
            };
        }
        private void notifyIcon1_Click(object sender, EventArgs e)
        {
            Show();
            WindowState = FormWindowState.Normal;
            notifyIcon1.Visible = false;
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            mainEdit.Refresh();
        }
    }
}